<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card>
      <!--添加角色按钮区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>

      <!--  角色列表区域-->
      <el-table :data="rolesList" border stripe>
        <!--展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag
                    closable
                    @close="removeRightById(scope.row,item1.psId)"
                >{{ item1.psName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级和三级权限-->
              <el-col :span="19">
                <!--二级权限-->
                <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable
                            @close="removeRightById(scope.row,item2.psId)"
                    >{{ item2.psName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--三级权限-->
                  <el-col :span="18">
                    <el-tag type="warning"
                            v-for="(item3) in item2.children"
                            :key="item3.id"
                            closable
                            @close="removeRightById(scope.row,item3.psId)"
                    >{{ item3.psName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       @click="showEditDialog(scope.row)"
                       icon="el-icon-edit">编辑
            </el-button>
            <el-button size="mini" type="danger"
                       @click="deleteRole(scope.row)"
                       icon="el-icon-delete">
              删除
            </el-button>
            <el-button size="mini"
                       type="warning"
                       icon="el-icon-setting"
                       @click="showSetRightDialog(scope.row)">
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--分配权限的对话框-->
    <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        @close="setRightDialogClose"
        width="50%"
    >
      <!--树形控件-->
      <el-tree :data="rightsList"
               :props="treeProps"
               node-key="psId"
               default-expand-all
               :default-checked-keys="defKeys"
               ref="treeRef"
               show-checkbox>

      </el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="closeRightDialog">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>

    <!-- 添加角色的对话框-->
    <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
        :close-on-click-modal="false ">

      <!-- 内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域-->
      <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 编辑角色的对话框-->
    <el-dialog
        title="编辑角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
        :close-on-click-modal="false ">

      <!-- 内容主体区域-->
      <el-form :model="editForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域-->
      <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      //添加角色对话框
      addDialogVisible: false,
      //编辑角色对话框
      editDialogVisible: false,

      //添加用户的表单验证对象
      addFormRules: {
        roleName: [
          //第一个message是为空的时候提示
          {required: true, message: "请输入角色名", trigger: 'blur'}, //trigger:'blur' 失去焦点触发验证
          {min: 2, max: 10, message: '角色名需要两个字符以上', trigger: 'blur'}
        ],
      },
      //添加角色表单
      addForm: {
        roleName: '',
        roleDesc: '',
      },
      editForm: {
        roleId: '',
        roleName: '',
        roleDesc: '',
      },
      //所有角色的列表数据
      rolesList: [],
      //展示分配权限的对话框
      setRightDialogVisible: false,
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: 'psName',
        children: 'children'
      },
      //默认的选中节点的Id值
      defKeys: [],
      //分配权限的角色ID
      roleId: '',
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {

    //添加角色操作
    async addRole() {
      const {data: res} = await this.$http.post('/roles', {
        roleName: this.addForm.roleName,
        roleDesc: this.addForm.roleDesc
      })
      if (res.meta.status !== 200) {
        return this.$message.error("添加角色失败");
      }
      this.$message.success("添加角色成功");
      await this.getRolesList();
      this.addDialogVisible = false;
    },

    //监听添加角色关闭事件
    addDialogClosed() {
      this.addDialogVisible = false
      this.addForm.roleName = ''
      this.addForm.roleDesc = ''
      this.addForm.roleId = ''
    },
    async showEditDialog(role) {
      const {data: res} = await this.$http.get(`/roles/${role.roleId}`)
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色失败");
      }
      this.editForm.roleName = res.data.roleName;
      this.editForm.roleDesc = res.data.roleDesc;
      this.editForm.roleId = res.data.roleId;
      console.log(res);
      this.editDialogVisible = true;
    },

    //编辑角色事件
    async editRole() {
      const {data: res} = await this.$http.put(`/roles/${this.editForm.roleId}`, {
        roleName: this.editForm.roleName,
        roleDesc: this.editForm.roleDesc
      })
      if (res.meta.status !== 200) {
        return this.$message.error("更新角色失败");
      }
      await this.getRolesList();
      this.editDialogVisible = false;
    },

    //监听编辑角色关闭事件
    editDialogClosed() {
      this.editDialogVisible = false;
      this.editForm.roleName = '';
      this.editForm.roleDesc = '';
    },

    //删除角色
    async deleteRole(role) {
      const resultConfirm = await this.$confirm("此操作将永久删除该角色，是否继续?","提示",{
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: 'warning'}).catch(err=>err)

      if (resultConfirm !== "confirm") {
        return this.$message.info("已取消删除操作")
      }

      const {data: res} = await this.$http.delete(`roles/${role.roleId}`);
      if (res.meta.status !== 200) {
        return this.$message.error("删除角色失败");
      }
      this.$message.success("删除角色成功");
      await this.getRolesList();

    },
    //获取所有角色列表
    async getRolesList() {
      const {data: res} = await this.$http.get("/roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败")
      }
      this.rolesList = res.data;
      console.log(this.rolesList)
    },
    //根据Id删除对应的权限
    async removeRightById(role, rightId) {
      console.log(role);
      //弹窗提示用户是否删除
      const confirmResult = await this.$confirm('是否删除此角色权限?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult);
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除!');
      } else {
        const {data: res} = await this.$http.delete(`roles/${role.roleId}/rights/${rightId}`)
        if (res.meta.status !== 200) {
          return this.$message.error("删除权限失败");
        }
        console.log(res);
        role.children = res.data.children;
      }
    },
    //展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.roleId;
      //获取所有权限的数据
      const {data: res} = await this.$http.get('rights/tree')
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限数据失败");
      }
      //把获取到的权限数据保存到data中
      this.rightsList = res.data;

      this.getLeafKeys(role, this.defKeys);
      console.log(this.defKeys);
      this.setRightDialogVisible = true;

    },
    //关闭分配权限对话框
    closeRightDialog() {
      this.setRightDialogVisible = false;
    },
    //通过递归的形式，获取角色下所有的三级权限id，并保存到defKeys数组中
    getLeafKeys(node, arr) {

      if (node.children.length === 0) {
        return arr.push(node.psId)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    //监听分配权限对话框的关闭事件
    setRightDialogClose() {
      this.defKeys = [];
    },
    //点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ];
      console.log(keys);
      const idStr = keys.join(',');
      const {data: res} = await this.$http.post(`/roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      await this.getRolesList();
      this.setRightDialogVisible = false;

    }
  }

}
</script>

<style scoped lang="less">

</style>